<?php
//load model
require('backend/models/categories.php');
require('libraries/pagination.php');

if (!empty($_POST['search'])) {
    header('location:admin.php?r=categories/index&q='.$_POST['search']);   
}

//xử lý tác vụ
if (isset($_POST['id'])) {
    if ($_POST['task']=='delete') {
        delete('categories', $_POST['id']);
    }
    if ($_POST['task']=='active') {
        status('categories', 1, $_POST['id']);
    }
    if ($_POST['task']=='deactive') {
        status('categories', 0, $_POST['id']);
    }
}

//phân trang
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$page = ($page>0) ? $page : 1;
$limit = 10;
$offset = ($page-1) * $limit;

$url = 'admin.php?r=categories/index';

//$sql = "SELECT * FROM table LIMIT $offset,$limit";
$options = array(
    'limit' => $limit,
    'offset' => $offset,
    'order_by' => 'id DESC'
);

//tìm kiếm
if (isset($_GET['q'])) {
    $url .= '&q='.$_GET['q'];
    $search = mysqli_real_escape_string($db, $_GET['q']);
    $search = trim($search);
    $search = preg_replace('/\s+/', ' ', $search);
    $words = explode(' ', $search);
    foreach($words as $word) {
        $like[] = "name LIKE '%$word%'";
    }
    $options['where'] = implode(' OR ', $like);
}

$total_rows = get_total('categories', $options);
$total = ceil($total_rows / $limit);

//dữ liệu truyền qua view
$title = 'Quản lý danh mục';
$categories = get_all('categories', $options);
$pagination = pagination($url, $page, $total);

//load view
$_content = 'backend/views/categories/index.phtml';
require('backend/views/common/layout.phtml');